package cn.lili.modules.payment.sentine;

import cn.lili.modules.kit.plugin.wechat.WechatPlugin;
import cn.lili.modules.payment.entity.dos.CombinePaymentLog;
import cn.lili.modules.payment.entity.dos.PaymentLog;
import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
import cn.lili.modules.payment.service.CombinePaymentLogService;
import cn.lili.modules.payment.service.PaymentLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 支付业务哨兵
 * <p>
 * 1、负责主动推送支付结果
 * 2、负责检测支付结果
 * 3、负责检测退款结果
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PaymentSentinelHandler {


    private final PaymentLogService paymentLogService;

    private final CombinePaymentLogService combinePaymentLogService;

    private final WechatPlugin wechatPlugin;

    public void backCheck() {
        //关闭，新逻辑无需检测
        //checkPayment();
        //checkRefund();
    }

    /**
     * 检测支付
     */
    private void checkPayment() {

        //非合单支付逻辑
        LambdaQueryWrapper<PaymentLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaymentLog::getIsPay, false);
        lambdaQueryWrapper.eq(PaymentLog::getIsCheck, false);
        lambdaQueryWrapper.eq(PaymentLog::getIsCombine, false);

        List<PaymentLog> paymentLogList = paymentLogService.list(lambdaQueryWrapper);

        for (PaymentLog paymentLog : paymentLogList) {
            try {
                if (paymentLog.getPaymentMethod().equals(PaymentMethodEnum.WECHAT.name())) {
                    wechatPlugin.checkPaymentResult(paymentLog);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //合单支付逻辑

        LambdaQueryWrapper<CombinePaymentLog> combineLambdaQueryWrapper = new LambdaQueryWrapper<>();
        combineLambdaQueryWrapper.eq(CombinePaymentLog::getIsCheck, false);

        List<CombinePaymentLog> combinePaymentLogs = combinePaymentLogService.list(combineLambdaQueryWrapper);

        for (CombinePaymentLog combinePaymentLog : combinePaymentLogs) {

            try {
                if (combinePaymentLog.getPaymentMethod().equals(PaymentMethodEnum.WECHAT.name())) {
                    wechatPlugin.checkPaymentResult(combinePaymentLog);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    /**
     * 检测退款
     */
    private void checkRefund() {
//
//        LambdaQueryWrapper<PaymentLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//
//        //重复支付、未退款的订单进行退款
//        lambdaQueryWrapper.eq(PaymentLog::getIsRepeat, true);
//        lambdaQueryWrapper.eq(PaymentLog::getIsRefund, false);
//
//        List<PaymentLog> paymentLogList = paymentLogService.list(lambdaQueryWrapper);
//
//        if (paymentLogList == null || paymentLogList.isEmpty()) {
//            return;
//        }
//
//        //回查支付状态
//        for (PaymentLog paymentLog : paymentLogList) {
//            try {
//                Payment payment = (Payment) SpringContextUtil.getBean(paymentLog.getPaymentMethod());
//
//                //生成新的退款申请流水号并持久化
//                paymentLog.setOutOrderNo(SnowFlake.getIdStr());
//                paymentLogService.saveOrUpdate(paymentLog);
//                payment.refund(paymentLog);
//                //支付成功后的业务逻辑
//                if (paymentLog.getIsPay()) {
//                    switch (paymentLog.getOrderType()) {
//                        case "TRADE":
//                            Trade trade = tradeClient.getBySn(paymentLog.getOrderSn());
//                            // 如果交易已超时，则标记重复，退款操作
//                            if (trade.getOrderStatus()
//                                    .equals(OrderStatusEnum.CANCELLED.name())) {
//                                paymentLog.setIsRefund(true);
//                            }
//                            //已支付,则判定交易流水是否一致,不一致则标记重复支付
//                            else if (!trade.getOrderStatus()
//                                    .equals(OrderStatusEnum.UNPAID.name())) {
//                                if (!trade.getReceivableNo()
//                                        .equals(paymentLog.getPayOrderNo())) {
//                                    paymentLog.setIsRefund(true);
//                                }
//                            }
//                            break;
//                        case "RECHARGE":
//                            Recharge recharge = rechargeService.getRecharge(paymentLog.getOrderSn());
//                            //已支付,则判定交易流水是否一致,不一致则标记重复支付
//                            if (recharge.getPayStatus()
//                                    .equals(PayStatusEnum.PAID.name())) {
//                                if (!recharge.getReceivableNo()
//                                        .equals(paymentLog.getPayOrderNo())) {
//                                    paymentLog.setIsRefund(true);
//                                }
//                            }
//                            break;
//                        default:
//                            break;
//                    }
//                    PaymentSuccessParams paymentSuccessParams = new PaymentSuccessParams(paymentLog);
//                    paymentService.success(paymentSuccessParams);
//
//                }
//                paymentLogService.saveOrUpdate(paymentLog);
//
//
//            } catch (Exception e) {
//                log.error("回查退款流程异常{}", JSONUtil.toJsonStr(paymentLog), e);
//            }
//        }
    }

    /**
     * 退款成功
     *
     * @param refundId      退款请求流水
     * @param transactionId 退款第三方返回流水
     */
    public void refundSuccess(String refundId, String transactionId) {
//        LambdaQueryWrapper<PaymentLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//
//        //重复支付、未退款的订单进行退款
//        lambdaQueryWrapper.eq(PaymentLog::getOutOrderNo, refundId);
//
//        PaymentLog paymentLog = paymentLogService.getOne(lambdaQueryWrapper, false);
//        if (paymentLog != null) {
//            paymentLog.setIsRefund(true);
//            paymentLog.setOutOrderNo(refundId);
//            paymentLog.setRefundReceivableNo(transactionId);
//            paymentLogService.saveOrUpdate(paymentLog);
//        }
    }

    /**
     * 退款成功
     *
     * @param refundId      退款请求流水
     * @param transactionId 退款第三方返回流水
     * @param summary       失败原因
     */
    public void refundError(String refundId, String transactionId, String summary) {
//        LambdaQueryWrapper<PaymentLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//
//        //重复支付、未退款的订单进行退款
//        lambdaQueryWrapper.eq(PaymentLog::getOutOrderNo, refundId);
//
//        PaymentLog paymentLog = paymentLogService.getOne(lambdaQueryWrapper, false);
//        if (paymentLog != null) {
//            paymentLog.setIsRefund(false);
//            paymentLog.setOutOrderNo(refundId);
//            paymentLog.setRefundReceivableNo(transactionId);
//            paymentLog.setRefundMessage(summary);
//            paymentLogService.saveOrUpdate(paymentLog);
//        }
    }
}
